<!-- 输入选择框

注：如果需要在弹窗上使用，需要设置最外层包裹是谁，wrapSelector，默认最外层包裹是body，select弹窗组件就会跟着body一起滚动
 -->
<template>
  <div class="m-input-select">
  	<a-input class="ipt" v-model:value="_d.label" :placeholder="props.placeholder"
  		autocomplete="off"
  		@click.stop
  		@focus="focusInput"
  		@change="changeInput" />
  </div>
</template>

<script setup>
	import { reactive, ref, computed, watch, onMounted } from 'vue'
	import {httpPost} from "@/api/index.js";
	import tSelect from "./tSelect.js";

	const emit = defineEmits(['update:label', 'update:value']);

	const props = defineProps({
		action: {
			type: String,
			default: ''
		},
		label: {
			type: String,
			default: ''
		},
		value: {
			type: String,
			default: ''
		},
		placeholder: {
			type: String,
			default: ''
		},
		fieldNames: {
			type: Object,
			default: () => ({})
		},
		maxHeight: {
			type: String,
			default: '264px'
		},
		// 包裹层
		wrapSelector: {
			type: String,
			default: 'body'
		}
	})

	const _d = reactive({
		label: props.label,
		value: props.value,

		aList: [],
		bList: [],

		fieldNames: Object.assign({label: 'label', value: 'value'}, props.fieldNames),

		oTSelect: null,
	})

	watch(() => props.label+'_'+props.value, () => {
		_d.label = props.label;
		_d.value = props.value;
		filterList();
	})

	onMounted(() => {
		getData();
	})

	


	function getData() {
		if(!props.action) {
			console.error('上传接口不能为空');
			return;
		}
		httpPost(props.action).then(res => {
			_d.aList = res;
			_d.bList = res;
		})
	}

	// 根据label过滤列表
	let timer = null;
	function filterList() {
		clearTimeout(timer);
		timer = setTimeout(() => {
			_d.bList = _d.aList.filter(item => item[_d.fieldNames.label].indexOf(_d.label) != -1);
			_d.oTSelect.changeList(_d.bList);
		}, 100);
	}

	function focusInput(e) {
		_d.bList = _d.aList;

		let dis = getDistanceBody(e.target);

		// 初始化下拉框
		_d.oTSelect = tSelect({
			top: dis.top + 32,
			left: dis.left,
			value: _d.value,
			list: _d.bList,
			fieldNames: _d.fieldNames,
			wrapSelector: props.wrapSelector,
			maxHeight: props.maxHeight,
			change: (item) => {
				emit('update:label', item[_d.fieldNames.label]);
				emit('update:value', item[_d.fieldNames.value]);
				_d.oTSelect.changeValue(_d.value);
			}
		});
	}

	function changeInput() {
		emit('update:label', _d.label);
		emit('update:value', '');
		_d.oTSelect.changeValue(_d.value);
	}

	// 获取节点到body的高度
	function getDistanceBody (obj) {
		var oBody = document.body;
		var oHtml = document.documentElement;
		var oParent = null;
		var oDistance = {
			top: 0,
			left: 0
		}
		do {
			oDistance.top += obj.offsetTop;
			oDistance.left += obj.offsetLeft;
			oParent = obj.offsetParent;
			obj = oParent;
		} while(oParent && oParent != oBody && oParent != oHtml)

		return oDistance;
	}

</script>

<style lang="less" scoped>
.m-input-select {
	position: relative;
	
}
</style>
